package com.braveo.dict;

import android.util.Base64;
import android.webkit.WebView;

public class BraveImageProvider {
	static final String DICT_IMG_PREFIX = "dictImg://";
	static final int DICT_IMG_LENGTH = DICT_IMG_PREFIX.length();
	
	private final ImageDataLoader dataLoader;
	
	public BraveImageProvider(ImageDataLoader dataLoader) {
		this.dataLoader = dataLoader;
	}

	public static int parseUrlFormImageId(String url) {
		if(url.startsWith(DICT_IMG_PREFIX))
		{
			return Integer.parseInt(url.substring(DICT_IMG_LENGTH));
		}
		return -1;
	}
	
	public boolean handleImageRequest(WebView view, String url, int imageId) {
		String pageData = createPageData(imageId);

		  String urlStr   = "http://example.com/my.jpg";
		  String mimeType = "text/html";
		  String encoding = null;

		  view.loadDataWithBaseURL(urlStr, pageData, mimeType, encoding, url);
		
		//view.loadData(imageData, image.getMimeType(), "base64");		
		
		return true;
	}

	public String createPageData(int imageId) {
		BraveImageObject image = dataLoader.loadImage(imageId);
		
		if (image == null) {
			return ""; // can't process
		}
		
		String imageData = Base64.encodeToString(image.getImageData(), Base64.DEFAULT);
		  String pageData = "<img src=\"data:" +
			  		image.getMimeType() +
			  		";base64," + imageData + "\" />";
		return pageData;
	}
}
